#include "Model.h"
#include "Vertex.h"
#include <string.h>
#include "FileManager.h"

void ReadFileNFG(const char* fileName, Vertex*& verticesData, int& numOfVertices, unsigned short*& indices, int& numOfIndices);

Model::Model(void)
{
	m_vboId = 0;
	m_iboId = 0;
	m_numOfVertices = 0;
	m_numOfIndices = 0;
}

Model::~Model(void)
{
	glDeleteBuffers(1, &m_vboId);
	glDeleteBuffers(1, &m_iboId);
}

void Model::Init(const char *fileName, const char *id)
{
	strcpy(m_id, id);

	Vertex *verticesData;
	unsigned short *indices;
	
	ReadFileNFG(fileName, verticesData, m_numOfVertices, indices, m_numOfIndices);

	//buffer object (VBO)
	glGenBuffers(1, &m_vboId);
	glBindBuffer(GL_ARRAY_BUFFER, m_vboId);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * m_numOfVertices, verticesData, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	//buffer index (IBO)
	glGenBuffers(1, &m_iboId);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboId);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * m_numOfIndices, indices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	delete verticesData;
	delete indices;
}

GLuint Model::GetVboID()
{
	return m_vboId;
}

GLuint Model::GetIboID()
{
	return m_iboId;
}

int Model::GetNumOfVertices()
{
	return m_numOfVertices;
}

int Model::GetNumOfIndices()
{
	return m_numOfIndices;
}

void ReadFileNFG(const char* fileName, Vertex*& verticesData, int& numOfVertices, unsigned short*& indices, int& numOfIndices)
{
	FileManager *fileManager = FileManager::GetInstance();
	FILE *pFile = fileManager->Open(fileName, "r");
	int tmp;

	if (pFile != NULL)
	{
		fscanf(pFile, "NrVertices: %d\n", &numOfVertices);
		verticesData = new Vertex[numOfVertices];
		for (int i = 0; i < numOfVertices; i++)
		{
			fscanf(pFile, "%d. pos:[%f, %f, %f]; norm:[%f, %f, %f]; binorm:[%f, %f, %f]; tgt:[%f, %f, %f]; uv:[%f, %f];\n", 
				&tmp, &verticesData[i].pos.x, &verticesData[i].pos.y, &verticesData[i].pos.z, 
				&verticesData[i].normal.x, &verticesData[i].normal.y, &verticesData[i].normal.z, 
				&verticesData[i].binormal.x, &verticesData[i].binormal.y, &verticesData[i].binormal.z, 
				&verticesData[i].tangent.x, &verticesData[i].tangent.y, &verticesData[i].tangent.z, 
				&verticesData[i].uv.x, &verticesData[i].uv.y);
		}

		fscanf(pFile, "NrIndices: %d\n", &numOfIndices);
		indices = new unsigned short[numOfIndices];

		for (int i = 0; i < numOfIndices; i += 3)
		{
			fscanf(pFile, "%d. %hu, %hu, %hu\n", &tmp, &indices[i + 0], &indices[i + 1], &indices[i + 2]);
		}
	}
	fclose(pFile);
}

const char* Model::GetID()
{
	return m_id;
}